package com.simen.hellobytes.android.image;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;

/**
 * author: SimenHi
 * create time: 2020-05-09 10:29
 * description:
 */
public class ImageUtil {

    public static Bitmap replacePngColorRes(Context context, int imgRes, int colorRes) {
        return replacePngColor(context,imgRes,context.getResources().getColor(colorRes));
    }

    /**
     * 将png图片非透明部分替换为指定颜色
     */
    public static Bitmap replacePngColor(Context context,int imgRes, int color) {
        Bitmap src= BitmapFactory.decodeResource(context.getResources(),imgRes);

        int width = src.getWidth();
        int height = src.getHeight();
        int[] pixels = new int[width * height];
        // get pixel array from source
        src.getPixels(pixels, 0, width, 0, 0, width, height);

        Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig());

        BitmapUtil.recycleBmp(src);

//        int A, R, G, B;
//        int pixel;

//        A = Color.alpha(color);
//        R = Color.red(color);
//        G = Color.green(color);
//        B = Color.blue(color);
//        int tempColor=Color.argb(A,R,G,B);

        // iteration through pixels
        for (int y = 0; y < height; ++y) {
            for (int x = 0; x < width; ++x) {
                // get current index in 2D-matrix
                int index = y * width + x;
                int pixel = pixels[index];

                if(pixel != Color.TRANSPARENT){
                    //change A-RGB individually
                    //pixels[index] = tempColor;

                    /*or change the whole color*/
                    pixels[index] = color;
                }
            }
        }
        bmOut.setPixels(pixels, 0, width, 0, 0, width, height);

        return bmOut;
    }

}
